<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>cssmoban</title>
    <!-- Bootstrap Styles-->
    <link href="../assets/css/bootstrap.css" rel="stylesheet" />
    <!-- FontAwesome Styles-->
    <link href="../assets/css/font-awesome.css" rel="stylesheet" />
    <!-- Morris Chart Styles-->

    <!-- Custom Styles-->
    <link href="../assets/css/custom-styles.css" rel="stylesheet" />
    <!-- Google Fonts-->
    <link href='https://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' />
    <!-- TABLE STYLES-->
    <link href="../assets/js/dataTables/dataTables.bootstrap.css" rel="stylesheet" />
    <link rel="stylesheet" href="../layui/css/layui.css" media="all">
    <script src="../layui/layui.js" charset="utf-8"></script>
    <style>
        .underline{
            border-bottom: 1px solid rgba(107, 108, 109, 0.19);
            background-color: rgb(50, 50, 50);
            color: rgb(50, 50, 50);
        }

    </style>
</head>
<body>
<div id="wrapper">
    <nav class="navbar navbar-default top-navbar" role="navigation" style="z-index: 80000">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".sidebar-collapse">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="index.html"><strong>后台管理系统</strong></a>

        </div>

        <ul class="nav navbar-top-links navbar-right">
            <li class="dropdown">
                <a class="dropdown-toggle" data-toggle="dropdown" href="#" aria-expanded="false">
                    <i class="fa fa-user fa-fw"></i> <span id="username"></span>
                </a>
                <ul class="dropdown-menu dropdown-user">
                    <li class="divider"></li>
                    <li><a href="../logOut"><i class="fa fa-sign-out fa-fw"></i>注销</a>
                    </li>
                </ul>
            </li>
        </ul>
    </nav>
    <!--/. NAV TOP  -->
    <nav class="navbar-default navbar-side" role="navigation" style="z-index: 0">
        <div class="sidebar-collapse">
            <ul class="nav" id="main-menu">

                <li>
                    <a href="../knowledge/admin.html#"><i class="fa fa-dashboard"></i>主页</a>
                </li>
                <li>
                    <a href="../folk/admin"><i class="fa fa-bar-chart-o"></i> 民间医药数据库</a>
                </li>
                <li id="collapse">
                    <a href="#"><i class="fa fa-qrcode"></i>传统知识数据库<span class="fa arrow"></span></a>
                    <ul class="nav nav-second-level">
                        <li>
                            <a href="../searchTcm"  class="underline" id="search">查询中医药知识</a>
                        </li>
                        <li>
                            <a href="../addTcm" class="underline" id="add">添加中医药知识</a>
                        </li>

                    </ul>
                </li>
                <li >
                    <a href="../user/userManage"><i class="fa fa-bar-chart-o"></i> 用户管理</a>
                </li>
            </ul>

        </div>
    </nav>
    <!-- /. NAV SIDE  -->
    <div id="page-wrapper" >



        <div id="page-inner" style="margin-top: 0;">
            <div class="row">
                <div class="col-md-12">

                    <!-- Advanced Tables -->
                    <div class="panel panel-default">
                        <div class="panel-body">
                            <div class="table-responsive">
                                <table id="demo" lay-filter="actions"></table>
                            </div>

                        </div>
                    </div>
                    <!--End Advanced Tables -->
                </div>
            </div>


</div>
    </div>

</div>
</body>
<script id="tool" type="text/html">
    <a class="layui-btn layui-btn-danger layui-btn-sm" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-danger layui-btn-sm" lay-event="add">添加</a>
</script>
<script type="text/html" id="endTool">
    <div>
        <button class="layui-btn layui-btn-sm" lay-event="edit"><i class="layui-icon">&#xe642;</i>编辑</button>
    </div>

</script>
<script src="../assets/js/jquery-1.10.2.js"></script>
<!-- Bootstrap Js -->
<script src="../assets/js/bootstrap.min.js"></script>
<!-- Metis Menu Js -->
<script src="../assets/js/jquery.metisMenu.js"></script>
<!-- DATA TABLE SCRIPTS -->
<script src="../assets/js/dataTables/jquery.dataTables.js"></script>
<script src="../assets/js/dataTables/dataTables.bootstrap.js"></script>
<!-- Custom Js -->
<script src="../assets/js/custom-scripts.js"></script>
<script>
    window.onload=function () {
        layui.use(['table'], function(){
            window.form = layui.form;
        });
    }

    var objs = []
    var content = $('<div  class="layui-row" id="addUser" lay-event="add"> ' +
        '    <form class="layui-form layui-form-pane" lay-filter="editFilter"  style="width: auto"> ' +
        '        <div class="layui-form-item">' +
        '            <label class="layui-form-label">用户名</label> ' +
        '            <div class="layui-input-block"> ' +
        '                <input type="text" id="usernameScan" name="username" lay-verify="required" autocomplete="off" placeholder="请输入用户姓名" class="layui-input">' +
        '            </div>' +
        '        </div> ' +
        '        <div class="layui-form-item"> ' +
        '            <label class="layui-form-label">密码</label> ' +
        '            <div class="layui-input-block"> ' +
        '                <input type="text" id="password" name="password" lay-verify="required|password" autocomplete="off" placeholder="请输入密码(6-12位)" class="layui-input"> ' +
        '            </div> ' +
        '        </div> ' +
        '        <div class="layui-form-item"> ' +
        '            <label class="layui-form-label">用户类型</label> ' +
        '            <div class="layui-input-inline"> ' +
        '                <select id="userType"> ' +
        '                    <option name="userType" value="">请选择用户身份</option> ' +
        '                    <option name="userType" value="普通用户" selected="">普通用户</option> ' +
        '                    <option name="userType" value="管理员">管理员</option> ' +
        '                </select> ' +
        '            </div> ' +
        '        </div> ' +
        ' ' +
        '    </form> ' +
        '</div>');
    var searchKeyWords = '';
    var idArr = []
    var urlTmp = '/knowledge/selectByName/?holderName='

    layui.use(['table'], function(){
        var table = layui.table;
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange=function () {
            if (xhr.readyState!=4||xhr.status!=200){
                return;
            }
            else
            $("#username").text(xhr.responseText)
        }
        xhr.open('GET', '../name');
        xhr.send();
        window.renderTable=function () {
            var table = layui.table;
            table.render({
                elem: '#demo'
                ,url: "../user/listUser"
                ,page: true
                ,method:'post'
                ,toolbar: '#tool'
                ,defaultToolbar:[]
                ,cols: [[
                    {type: 'checkbox', fixed: 'left',width: 60}
                    ,{field:'id',width:80,title:'ID',align:'center'}
                    ,{field:'username', title: '用户姓名',align: 'center'}
                    ,{field:'password', width:120, title: '用户密码',align: 'center'}
                    ,{field:'user_type',  width:120, title: '用户类型',align: 'center'}
                    ,{field:'creation_date',width:120, title: '创建时间',align: 'center'}
                    ,{ title: '操作',align: 'center',templet:'#endTool'}
                ]]
            });
        }
        renderTable('../knowledge/selectAll')
        table.on('tool(actions)',function (obj) {
            var  data = obj.data;
            if (obj.event === 'edit'){
                layer.open({
                    type: 0,
                    //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                    title: "编辑",
                    skin: "layui-layer-rim",
                    area: ['800px', '600px'],
                    btn: ['确定'],
                    content: content.html(),
                    success:function(){
                      setFormValue(data)
                    },
                    yes: function (index) {
                        var username = $("#usernameScan").val().trim();
                        var password = $("#password").val();
                        var type=$("#userType option:selected").val();
                        if (username&&password&&type){
                            var reg = /^[\S]{6,20}$/
                            if (reg.test(password)){
                                $.ajax({
                                    url: "../user/updateUser",
                                    type: "POST",
                                    data:{
                                        id:data.id,
                                        username: username,
                                        password: password,
                                        userType: type
                                    },
                                    dataType: 'json',
                                    success: function(data){

                                        if(data.code==1){
                                            layer.close(index);
                                            layer.msg("编辑成功", {icon: 6});
                                            renderTable('../user/listUser');
                                        }else{
                                            layer.msg("编辑失败", {icon: 5});
                                        }
                                    }
                                })
                            }
                            else {
                                layer.msg('修改失败,用户密码为6-20位')
                            }

                        }
                        else {
                            layer.msg('请将表单填写完毕')
                        }

                    }
                })
                //setFormValue(data);//动态向表单中赋值
            }
        })
        table.on('toolbar(actions)', function(obj){
            var checkStatus = table.checkStatus(obj.config.id)
                ,data = checkStatus.data; //获取选中的数据
            switch(obj.event){
                case 'del':
                    idArr=[];
                    var flag=true;
                    data.forEach(function (item, index) {
                        if (item.user_type=='普通用户')
                        idArr.push(item.id)
                        else{
                            flag=false
                        }
                    })
                    if (!flag){
                        layer.msg('无法删除管理员账户');
                    }
                    if (idArr.length>0&&flag==true) {
                        $.post('../user/removeUsers', {id: idArr, length: idArr.length}, function (res) {
                            if (res.code == 1) {

                                layer.msg('删除成功')
                                objs.forEach(function (value) {
                                    if (value.data.user_type=='普通用户')
                                    value.del()
                                })
                            }
                            else {
                                layer.msg('删除失败')
                                renderTable('../user/listUser')
                            }
                        })
                    }
                    break;
                case 'add':
                    layer.open({
                        type: 0,
                        title: "添加用户",
                        skin: "layui-layer-rim",
                        area: ['600px','600px'],
                        content: content.html(),
                        btn: ['确定'],
                        yes: function (index) {
                            var username = $("#usernameScan").val().trim();
                            var password = $("#password").val();
                            var type=$("#userType option:selected").val();
                            if (username&&password&&type){
                                var reg = /^[\S]{6,20}$/
                                if (reg.test(password)){
                                    $.ajax({
                                        url: "../user/addUser",
                                        type: "POST",
                                        data:{
                                            id:data.id,
                                            username: username,
                                            password: password,
                                            userType: type
                                        },
                                        dataType: 'json',
                                        success: function(data){
                                            console.error($("#addUser"))
                                            if(data.code==1){
                                                layer.close(index);
                                                layer.msg("添加成功", {icon: 6});
                                                renderTable('../user/listUser');
                                            }else if (data.code == 105 ) {
                                                layer.msg("用户名已存在", {icon: 5});
                                                layer.close(index)
                                            }else{
                                                layer.close(index)
                                                layer.msg('添加失败', {icon: 5});
                                            }
                                        },
                                        fail:function () {
                                            layer.close(index);
                                            layer.msg('请求失败', {icon: 5});
                                        }
                                    })
                                }
                                else {
                                    layer.msg('添加失败,用户密码为6-20位')
                                }
                            }
                            else{
                                layer.msg('请将表单填写完毕')
                            }
                        }


                    });
                    setFormValue(data)
                    break;
            }
        });
        //监听表格复选框选择
        table.on('checkbox(actions)', function(obj){
            objs.push(obj)
            objs=objs.filter(function (item) {
                return item.checked===true
            })
        });

    });
</script>
<script>
    function setFormValue(data) {
        $('option[value='+data.user_type+']').attr('selected',true)
        form.val("editFilter", {
            "username": data.username,
            "password":data.password,
        })
    }
</script>

</html>

